<template>
  <div style="margin: 20px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px" class="globalSerchFormStyle">
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId" size="small">
            <el-select
              style="width: 180px"
              v-model="queryParams.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel === '1'">
          <el-form-item label="油站名称" prop="stationId" clearable>
            <el-select v-model="queryParams.stationId" :clearable="true" filterable placeholder="请选择油站" style="width: 190px">
              <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName" :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="nickName" size="small">
              <el-input v-model="queryParams.nickName" placeholder="请输入员工姓名" style="width: 190px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工账号" prop="userName" size="small">
              <el-input v-model="queryParams.userName" placeholder="请输入员工账号" style="width: 190px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号" prop="phonenumber" size="small">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号" style="width: 190px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交易时间" prop="payTimeId" size="small" >
              <el-select v-model="queryParams.payTimeId" :clearable="true" filterable placeholder="请选择交易日期" style="width: 190px">
                <el-option v-for="item in payTimeList" :key="item.payTimeId" :label="item.text" :value="item.payTimeId">
                </el-option>
            </el-select>
            </el-form-item>
          </el-col>
         <el-col :span="6"  v-if="queryParams.payTimeId==5">
          <el-form-item label="交易时间"size="small"  >
           <el-date-picker size="mini" style="margin: 0px 10px; width: 230px" v-model="dateRangeCreatedDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" align="right" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
            </el-form-item>
          </el-col> 
      </el-row>
    </el-form>
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" class="fcous" @click="handleQuery" >搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery" plain >重置</el-button>
      </el-col>
    </el-row>
      <div class="common_modle">
        <div class="common_name"><p>扫码次数总计：</p><p>{{scanNum||0}}次</p></div>
        <div class="common_name"><p>支付金额总计：</p><p>{{moneySum||0}}元</p></div>
      </div>
     <el-table stripe style="width: 100%" :data="list" ref="orderTable"  v-loading="loading">
      <el-table-column label="油站名称" align="center" prop="stationName" />
      <el-table-column label="员工账号" align="center" prop="userName" />
      <el-table-column label="员工姓名" align="center" prop="nickName" />
      <el-table-column label="员工手机号" align="center" prop="phonenumber" />
      <el-table-column label="微信支付金额（元）" align="center" prop="wxAmt" />
      <el-table-column label="支付宝支付金额（元）" align="center" prop="zfbAmt" />
      <el-table-column label="电子卡支付金额（元）" align="center" prop="dzkAmt" />
      <el-table-column label="扫码次数（次）" align="center" prop="count" />
      <af-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showDetails(scope.row)">详情</el-button>
        </template>
      </af-table-column>
    </el-table> 
    <el-pagination class="fr" style="margin-top: 8px" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40,50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"/> 
    <el-drawer title="详情" :visible.sync="drawer" :direction="direction" >
      <el-row class="el_row">
        <span>油站名称：{{details.stationName}}</span>
        <span>员工姓名：{{details.userName}}</span>
        <span>员工账号：{{details.accountNumber}}</span>
        <span>员工手机号：{{details.phonenumber}}</span>
      </el-row>
      <el-row class="el_row">
        <span>交易时间：{{timeInterval.startTime}}  至  {{timeInterval.endTime}}</span>
      </el-row>
      <el-table :data="gridData" border v-loading="loading2">
      <el-table-column property="orderNo" label="订单号" width="150"></el-table-column>
      <el-table-column property="receivableAmt" label="应付金额(元)" width="150"></el-table-column>
      <el-table-column property="amt" label="实付金额(元)" width="150"></el-table-column>
      <el-table-column property="consumer" label="客户姓名" width="150"></el-table-column>
      <el-table-column property="customerPhone" label="客户手机号" width="150"></el-table-column>
      <el-table-column property="payTypeName" label="支付方式" width="150"></el-table-column>
      <el-table-column property="createdDate" label="支付时间" width="150"></el-table-column>
    </el-table>
    <el-pagination class="fr" style="margin-top: 8px" @size-change="handleSizeChange2" @current-change="handleCurrentChange2" :current-page="page2" :page-sizes="[10, 20, 40,50]" :page-size="pageSize2" layout="total, sizes, prev, pager, next, jumper" :total="total2"/> 
    </el-drawer>
  </div>
</template>

<script>
import {getPayOrderEmployee,getPayOrderStatistics,getPayOrderDetail} from "@/api/station/personnel";
import {
  enterpriseList,
} from "@/api/station/order";
import getUserProfileName from "@/utils/getUserProfile";
import { listEnterpriseStation, getStationByEnterprise,} from "@/api/dept";
export default {
  data() {
    return {
      // 查询参数
      queryParams:{
        payTimeId:1,
        enterpriseId:null,
      },
      enterpriseList: [],
      stationList:[],
      payTimeList:[
          {payTimeId:1,text:'今日'},
          {payTimeId:2,text:'昨日'},
          {payTimeId:3,text:'近一周'},
          {payTimeId:4,text:'近一月'},
          {payTimeId:5,text:'自定义'},
      ],
      list:[1],
      loading: false,
      loading2:false,
      drawer:false,
      gridData: [],
      page: 1,
      pageSize: 10,
      page2: 1,
      pageSize2: 10,
       // 总条数
      total: 0,
       // 总条数
      total2: 0,
      direction: 'rtl',
      dateRangeCreatedDate: [],//搜索时间区间
      moneySum:null,//收款总数
      scanNum:null,//扫码次数
      timeInterval:{ 
        startTime:'',
        endTime:''
      },//详情交易时间
      details:{},
      detailsParams:{}
    };
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    isEnterprise() {
      let userLevel = this.$store.state.user.userLevel;
      if (userLevel === "1") {
        return true;
      } else {
        this.dialogForm.stationId = this.$store.state.user.stationId;
        return false;
      }
    },
  },
  created(){
     // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      // console.log("是油企账号")
      this.getStationList(this.presentEnterprise.enterpriseId);
    } else {
      // console.log("不是油企账号")
      this.getStationList();
    }
    this.getEnterpriseList();
  },
  mounted(){
    this.handleQuery()
  },
  methods:{ 
    // 获取统计次数和金额总数
    async getSumData(params){
      const res= await getPayOrderStatistics(params)
      if(res&&res.code==200){ 
        this.moneySum=res&&res.data&&res.data.total
        this.scanNum=res&&res.data&&res.data.count
      }else{ 
        this.$message.error(res&&res.msg)
      }
    },
   getPayTypeText(payType) {
    // 根据 payType 返回相应的文字
    switch (payType) {
      case 'wx':
        return '微信支付';
      case 'zfb':
        return '支付宝支付';
       case 'dzk':
        return '电子卡支付';
      default:
        return '未知支付方式';
    }
  },
     // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 根据油企获取油站
    handleSelectChange(value) {
      this.queryParams.stationId = null;
      this.getStationList(value);
    },
    // 查询油站
    async getStationList(val) {
      // 判断是不是admin账号
      const isDelete = await getUserProfileName();
      if (isDelete) {
        // 是
        listEnterpriseStation({ enterpriseId: val }).then((res) => {
          console.log("是admin账号,油站名称", res);
          this.stationList = res;
        });
      } else {
        // 不是
        const res = await getStationByEnterprise();
        console.log("不是admin账号,油站名称", res);
        this.stationList = res.data;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams={payTimeId:1}
      this.dateRangeCreatedDate=[]
      this.getData();
    },
    async showDetails(rows){
      this.details={ 
        stationName:rows.stationName,
        userName:rows.oilPersonnelName,
        accountNumber:rows.userName,
        phonenumber:rows.phonenumber,
        
      }
      this.detailsParams={ 
        oilPersonnelId:rows.oilPersonnelId,
        beginTime:this.timeInterval.startTime,
        endTime:this.timeInterval.endTime,
        pageNum:this.page2,
        pageSize:this.pageSize2
      }
      this.getDetails(this.detailsParams)
      this.drawer=true
    },
    async getDetails(params){
      this.loading2=true
      const res=await getPayOrderDetail(params)
      if(res&&res.code==200){ 
        this.gridData=res.rows
        this.total2=res.total
      }else{ 
        this.$message.error(res&&res.msg)
      }
      this.loading2=false
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData();
    },
    handleSizeChange2(size) {
      this.pageSize2 = size;
      this.detailsParams.pageSize=this.pageSize2 
      this.getDetails(this.detailsParams)
    },
    handleCurrentChange2(page) {
      this.page2 = page;
      this.detailsParams.pageNum=this.page2 
      this.getDetails(this.detailsParams)
    },
    async getData() {
      if(this.loading) return
      this.loading=true
      let day;
      let query=this.queryParams
      query['pageNum']=this.page
      query['pageSize']=this.pageSize
      query['enterpriseId']=this.presentEnterprise&&this.presentEnterprise.enterpriseId||query['enterpriseId']
      switch (query.payTimeId) {
        case 1: // 今日
          query.beginTime = this.dateCalculate() + " " + "00:00:00";
          query.endTime = this.dateCalculate() + " " + "23:59:59";
          break;
        case 2: // 昨天
          query.beginTime = this.dateCalculate(-1) + " " + "00:00:00";
          query.endTime = this.dateCalculate(-1) + " " + "23:59:59";
          break;
        case 3: // 本周
          day = new Date().getDay();
          day = day === 0 ? 7 : day;
          day = -(day - 1);
          query.beginTime = this.dateCalculate(day) + " " + "00:00:00";
          query.endTime = this.dateCalculate() + " " + "23:59:59";
          break;
        case 4: // 本月
          day = new Date().getDay();
          let datetime = new Date();
          let month = new Date().getMonth() + 1;
          if (month < 10) month = `0${month}`;
          query.beginTime =
            datetime.getFullYear() + "-" + month + "-01" + " " + "00:00:00";
          //query.beginTime = this .dateCalculate(day);
          query.endTime = this.dateCalculate() + " " + "23:59:59";
          break;
        case 5: // 指定日期
          if (this.dateRangeCreatedDate == null) {
            this.dateRangeCreatedDate = [];
          }
          query.beginTime = this.dateRangeCreatedDate[0];
          query.endTime = this.dateRangeCreatedDate[1];
        default:
      }
      if(query.payTimeId==5&&query.beginTime==undefined&&query.endTime===undefined){ 
        this.$message.warning('请选择交易日期')
        this.loading=false
        return
      }
      this.timeInterval={startTime:query.beginTime,endTime:query.endTime} 
      this.getSumData(query)
      const res=await getPayOrderEmployee(query)
        if (res && res.code === 200) {
          this.list = res.rows;
          this.total = res.total;
        } else {
          this.list = [];
          this.total = 0;
        }
        this.loading = false;
    },
    dateCalculate(num = 0, date = false) {
      if (!date) {
        date = new Date(); //没有传入值时,默认是当前日期
        date =
          date.getFullYear() +
          "-" +
          (date.getMonth() + 1) +
          "-" +
          date.getDate();
      }
      date += " 00:00:00"; //设置为当天凌晨12点
      date = date.replace(/-/g, "/");
      date = Date.parse(new Date(date)) / 1000; //转换为时间戳
      date += 86400 * num; //修改后的时间戳
      var newDate = new Date(parseInt(date) * 1000); //转换为时间
      let month = newDate.getMonth() + 1;
      let sun = newDate.getDate();
      if (month < 10) month = `0${month}`;
      if (sun < 10) sun = `0${sun}`;
      return `${newDate.getFullYear()}-${month}-${sun}`;
    },
  }
};
</script>

<style lang="scss" scoped>
.common_modle{ 
  display: flex;
  align-items: center;
  .common_name{ 
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 56px;
    line-height: 56px;
    p:last-child{ 
      font-size: 15px;
      font-weight: bold;
      color: #02aff4;
    }
  }
  .common_name:last-child{ 
    margin-left: 20px;
  }
}
::v-deep .el-drawer__header{ 
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
::v-deep .el-drawer { 
  width: 50% !important;
  padding: 0px 30px;
}
::v-deep .el-drawer__header{
  margin-bottom: 0;
}
::v-deep .el_row{ 
  margin: 20px 0;
  span{ 
    padding-left: 40px;
  }
  span:first-child{ 
    padding-left: 0;
  }
}

</style>
